package com.xiaogao.vod.controller;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.xiaogao.commonUtils.Result;
import com.xiaogao.serviceBase.utils.exceptionHandler.XiaoGaoException;
import com.xiaogao.vod.service.VideoService;
import com.xiaogao.vod.utils.ConstantVodUtils;
import com.xiaogao.vod.utils.InitVodClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

@Api(description="阿里云视频点播微服务")
@RestController
@RequestMapping("/eduvod/video")
//@CrossOrigin
public class VideoController {

    @Resource
    private VideoService videoService;

    @ApiOperation(value = "上传视频到阿里云")
    @PostMapping("/uploadVideo")
    public Result uploadAlyVideo(
            @ApiParam(name = "file",value = "文件",required = true)
            @RequestParam("file") MultipartFile file) {
        String videoId = this.videoService.uploadAlyVideo(file);
        return Result.ok().message("视频上传成功！").data("videoId",videoId);
    }

    @ApiOperation(value = "删除视频")
    @DeleteMapping("/removeVideo/{videoId}")
    public Result removeVideo(
            @ApiParam(name = "videoId", value = "云端视频id", required = true)
            @PathVariable String videoId){

        videoService.removeVideo(videoId);
        return Result.ok().message("删除视频成功！");
    }

    @ApiOperation(value = "批量删除视频")
    @DeleteMapping("/removeVideoList")
    public Result removeVideoList(
            @ApiParam(name = "videoList",value = "云端视频id",required = true)
            @RequestParam("videoList") List<String> videoList){

        videoService.removeVideoList(videoList);
        return Result.ok().message("删除成功！");
    }

    @ApiOperation(value = "根据视频id获取视频凭证")
    @GetMapping("/getVideoPlayAuth/{videoId}")
    public Result getVideoPlayAuth(@PathVariable("videoId")String videoId){
        try {
            // 获取阿里云存储相关常量
            String accessKeyId = ConstantVodUtils.ACCESS_KEY_ID;
            String accessKeySecret = ConstantVodUtils.ACCESS_KEY_SECRET;

            // 初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(accessKeyId,accessKeySecret);
            // 创建获取凭证 request请求 和 response响应 对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            // 向request中设置视频id
            request.setVideoId(videoId);
            // 得到播放凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            // 返回结果
            return Result.ok().message("获取播放凭证成功").data("playAuth",playAuth);
        }catch (Exception e){
            throw new XiaoGaoException(20001,"获取凭证失败！");
        }
    }


}
